<template>
  <cl-crud ref="Crud">
    <cl-row>
      <cl-refresh-btn />
      <cl-add-btn />
      <cl-multi-delete-btn />
      <cl-flex1 />
    </cl-row>

    <cl-row>
      <cl-table ref="Table">
        <template #column-image="{ scope }">
          <cl-image :src="scope.row.image" :width="40" :height="40" />
        </template>
      </cl-table>
    </cl-row>

    <cl-upsert ref="Upsert">
      <template #slot-parentId="{ scope }">
        <el-tree-select
          v-model="scope.parentId"
          :data="categoryTree"
          :props="treeProps"
          clearable
          placeholder="请选择上级分类"
        />
      </template>
    </cl-upsert>
  </cl-crud>
</template>

<script lang="ts" setup>
import { useCrud, useTable, useUpsert } from '@cool-vue/crud'
import { ref, onMounted, nextTick } from 'vue'
import { useCool } from '/@/cool'
import { useI18n } from 'vue-i18n'

const { service } = useCool()
const { t } = useI18n()

// 分类树（用于树表和上级分类选择）
const categoryTree = ref<any[]>([])
const treeProps = { label: 'name', value: 'id', children: 'children' }
const flatCategoryList = ref<any[]>([])

function flattenTree(tree) {
  const result: any[] = []
  const walk = (list: any[]) => {
    if (!Array.isArray(list)) return
    for (const node of list) {
      result.push(node)
      if (node.children && node.children.length) walk(node.children)
    }
  }
  walk(tree)
  return result
}

// 拉取树结构（刷新列表和选择框用）
const fetchCategoryTree = async () => {
  const res = await service.base.goodsCategory.tree()
  categoryTree.value = res?.data ?? []
  flatCategoryList.value = flattenTree(categoryTree.value)
}
onMounted(fetchCategoryTree)

// cl-table 配置，支持树状展示
const Table = useTable({
  type: 'tree',
  columns: [
    { type: 'selection', width: 60 },
    { label: t('名称'), prop: 'name', minWidth: 150 },
    {
      label: t('上级分类'),
      prop: 'parentId',
      minWidth: 120,
      formatter({ row }) {
        if (!row || row.parentId == null || row.parentId === 0) return t('无')
        const find = flatCategoryList.value.find((cat: any) => cat.id === row.parentId)
        return find ? find.name : row.parentId
      }
    },
    {
      label: t('图片'),
      prop: 'image',
      width: 60,
      component: { name: 'cl-image' }
    },
    { label: t('说明'), prop: 'description', minWidth: 120 },
    { label: t('排序'), prop: 'sort', width: 80 },
    { label: t('分站ID'), prop: 'siteId', width: 80 },
    { label: t('创建时间'), prop: 'createTime', minWidth: 140 },
    {
      type: 'op',
      width: 200,
      buttons({ scope }) {
        return [
          {
            label: t('新增下级'),
            type: 'primary',
            onClick({ scope }) {
              append(scope.row)
            }
          },
          'edit',
          'delete'
        ]
      }
    }
  ]
})

// cl-upsert 配置
const Upsert = useUpsert({
  dialog: { width: '600px' },
  items: [
    {
      prop: 'name',
      label: t('名称'),
      required: true,
      component: { name: 'el-input', props: { placeholder: t('请输入分类名称') } }
    },
    {
      prop: 'parentId',
      label: t('上级分类'),
      component: { name: 'slot-parentId' }
    },
    {
      prop: 'image',
      label: t('图片'),
      component: { name: 'cl-upload', props: { accept: 'image/*', placeholder: t('上传图片') } }
    },
    {
      prop: 'description',
      label: t('说明'),
      component: { name: 'el-input', props: { type: 'textarea', rows: 2, placeholder: t('请输入说明') } }
    },
    {
      prop: 'sort',
      label: t('排序'),
      component: { name: 'el-input-number', props: { min: 0, placeholder: t('请输入排序') } }
    },
    {
      prop: 'siteId',
      label: t('分站ID'),
      required: true,
      component: { name: 'el-input-number', props: { min: 1, placeholder: t('请输入分站ID') } }
    }
  ],
  async onOpened() {
    await fetchCategoryTree()
    await nextTick()
  }
})

// cl-crud 配置
const Crud = useCrud(
  {
    service: service.base.goodsCategory,
    onRefresh(params, { render }) {
      // 注意这里用 list/page/tree，list返回树形即可
      service.base.goodsCategory.tree(params).then(res => {
        fetchCategoryTree()
        // 渲染树形结构
        render({
          ...res,
          data: flattenTree(res?.data ?? [])
        })
      })
    }
  },
  app => {
    app.refresh()
  }
)

// 新增下级
function append({ id }) {
  Crud.value?.rowAppend({
    parentId: id
  })
}
</script>
